package com.cpit.platform.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.cpit.platform.log.LogOperator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class HttpClientUtil {

	private static final String loggerName = HttpClientUtil.class.getClass().getName();
	private CloseableHttpClient httpclient = null;
	@SuppressWarnings("unused")
	private boolean needLogin = false;
	@SuppressWarnings("unused")
	private String loginUrl = null;
	@SuppressWarnings("unused")
	private String loginUsername = null;
	@SuppressWarnings("unused")
	private String loginPassword = null;
	
	private static final String APPLICATION_JSON = "application/json";
	private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
	
	public HttpClientUtil(String loginUrl, String username, String password) {
		needLogin = true;
		httpclient = HttpClients.createDefault();
		Map<String, Object> loginMap = new HashMap<String, Object>();
		loginMap.put("username", username);
		loginMap.put("password", password);
		postForm(loginUrl, loginMap);
	}
	
	public HttpClientUtil() {
		needLogin = false;
		httpclient = HttpClients.createDefault(); 
	}

	public void close() {
		try {  
			httpclient.close();  
		} catch (IOException e) {  
		}
	}
	
	public String get(String url) {  
		
		String ret = "";
		CloseableHttpResponse response = null;
		try {  
			// 创建httpget.    
			HttpGet httpget = new HttpGet(url);  
			// 执行get请求.    
			response = httpclient.execute(httpget);  
			// 获取响应实体    
			HttpEntity entity = response.getEntity();  
			// 打印响应状态    
			if (entity != null) {
					ret = EntityUtils.toString(entity, "UTF-8");
			}  
		} catch (ClientProtocolException e) {
			LogOperator.debug(loggerName, "get exception", e);
			return null;
		} catch (ParseException e) {
			LogOperator.debug(loggerName, "get exception", e);
			return null;
		} catch (IOException e) {
			LogOperator.debug(loggerName, "get exception", e);
			return null;
		} finally {  
			// 关闭连接,释放资源    
			try {  
				response.close();  
			} catch (Exception e) {
			}
		}
		return ret;
	}

	public String getWithHeader(String url, Map<String, String> headers) {
		String ret = "";
		CloseableHttpResponse response = null;
		try {
			HttpGet httpget = new HttpGet(url);
			// add header
			if(headers != null && headers.keySet().size() > 0) {
				Set<String> keys = headers.keySet();
				Iterator<String> keysIt = keys.iterator();
				while(keysIt.hasNext()) {
					String key = keysIt.next();
					String value = headers.get(key);
					httpget.setHeader(key, value);
				}
			}
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				ret = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (ClientProtocolException e) {
			LogOperator.debug(loggerName, "get exception", e);
			return null;
		} catch (ParseException e) {
			LogOperator.debug(loggerName, "get exception", e);
			return null;
		} catch (IOException e) {
			LogOperator.debug(loggerName, "get exception", e);
			return null;
		} finally {
			// 关闭连接,释放资源
			try {
				response.close();
			} catch (Exception e) {
			}
		}
		return ret;
	}

	public String postForm(String url, Map<String, Object> paras) {  
		// 创建httppost    
		HttpPost httppost = new HttpPost(url);  
		String ret = "";
		CloseableHttpResponse response = null;
		// 创建参数队列    
		List<NameValuePair> formparams = new ArrayList<NameValuePair>(); 
		Set<String> keySet = paras.keySet();
		for(String key : keySet) {
			String value = paras.get(key).toString();
			formparams.add(new BasicNameValuePair(key, value));  
		}
		UrlEncodedFormEntity uefEntity;  
		try {  
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");  
			httppost.setEntity(uefEntity);  
			response = httpclient.execute(httppost);  
			HttpEntity entity = response.getEntity();  
			if (entity != null) {
				ret = EntityUtils.toString(entity, "UTF-8");
			}  
		} catch (ClientProtocolException e) {  
			e.printStackTrace();  
		} catch (UnsupportedEncodingException e1) {  
			e1.printStackTrace();  
		} catch (IOException e) {  
			e.printStackTrace();  
		} finally {  
			// 关闭连接,释放资源
			try {  
				response.close();  
			} catch (Exception e) {
			}
		}
		return ret;
	}  

	public String postJson(String url, String json) {  
		// 创建httppost    
		HttpPost httppost = new HttpPost(url);
		httppost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
		String ret = "";
		CloseableHttpResponse response = null;
		try {  
			StringEntity se = new StringEntity(json);
			se.setContentType(CONTENT_TYPE_TEXT_JSON);
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
			httppost.setEntity(se);
			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();  
			if (entity != null) {
				ret = EntityUtils.toString(entity, "UTF-8");
			}  
		} catch (ClientProtocolException e) {  
			e.printStackTrace();  
		} catch (UnsupportedEncodingException e1) {  
			e1.printStackTrace();  
		} catch (IOException e) {  
			e.printStackTrace();  
		} finally {  
			// 关闭连接,释放资源
			try {  
				response.close();  
			} catch (Exception e) {
			}
		}
		return ret;
	} 
	
	public static String convert2Json(Object obj) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
		String json = null;
		try {
			json = mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new Exception(e);
		}
		return json;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object convert2Object(String json, Class clazz) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
		try {
			return mapper.readValue(json, clazz);
		} catch (JsonProcessingException e) {
			throw new Exception(e);
		}
	}
	
	// test get
	public static void main1(String[] s) {
		HttpClientUtil u = new HttpClientUtil("http://localhost:8080/omc/login", "root", "root11");
		System.out.println(u.get("http://localhost:8080/omc/security/user/getAllAccounts?_search=false&nd=1461219863157&rows=20&page=1&sidx=accountName&sord=asc"));
		u.close();
	}

	// test postJson
	public static void main2(String[] s) {
		String accoutJson = "{\"accountName\":\"test22\",\"accountDisplayName\":\"test22\",\"accountDesc\":\"\",\"accountRoles\":[\"readonly\"],\"eMail\":\"a@b.c\",\"accountPassword\":\"test11\",\"mobilePhone\":\"123123123\",\"officePhone\":\"123123123\"}";
		HttpClientUtil u = new HttpClientUtil("http://localhost:8080/omc/login", "root", "root11");
		System.out.println(u.postJson("http://localhost:8080/omc/security/user/newUserInfo", accoutJson));
		u.close();
	}
		
}
